package org.rain.core.dict.support;

import org.rain.common.CommonApi;
import org.rain.common.anno.Dict;
import org.rain.common.util.Strs;
import org.rain.core.dict.IDictParse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * created by yangtong on 2025/4/8 15:50:18
 * <br/>
 */
@Component
public class DefaultDictParseImpl implements IDictParse {

    private final Map<Class<?>, String> dictCache = new ConcurrentHashMap<>();

    @Autowired
    private CommonApi commonApi;

    /**
     * 获取一个类里面的所有字典元信息
     */
    @Override
    public <T> Map<String, String> parseClassDict(Class<T> clazz) {
        String dictStr = dictCache.get(clazz);
        if (dictStr == null) {
            StringJoiner sj = new StringJoiner("|");
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Dict.class)) {
                    String fieldName = field.getName();
                    Dict annotation = field.getAnnotation(Dict.class);
                    String table = annotation.table();
                    String code = annotation.code();
                    String text = annotation.text();
                    //表字典
                    if (Strs.isNotEmpty(table)) {
                        sj.add(fieldName + ":" + table + "," + code + "," + text);
                    }
                    //普通字典
                    else {
                        sj.add(fieldName + ":" + code);
                    }
                }
            }
            dictStr = sj.toString();
            dictCache.put(clazz, dictStr);
        }
        //dictStr表示一个类中配置的字典信息：sex:sexDict|name:user,id,realName|age:ageDict
        String[] dictItems = dictStr.split("\\|");
        Map<String, String> dictMap = new ConcurrentHashMap<>();
        for (String dictItem : dictItems) {
            //kv的合法格式应该是以冒号分隔的键值对
            String[] kv = dictItem.split(":", 2);
            if (kv.length == 2) {
                dictMap.put(kv[0], kv[1]);
            }
        }
        return dictMap;
    }

    @Override
    public <T> Map<String, String> translate(Map<String, String> classDict, Collection<T> data) {
        return Map.of();
    }

    @Override
    public <T> Map<String, String> translate(Map<String, String> classDict, T data) {
        return Map.of();
    }

}
